package com.bdd.crowd.service.impl;

import com.bdd.crowd.constant.CrowdConstant;
import com.bdd.crowd.entity.Admin;
import com.bdd.crowd.entity.AdminExample;
import com.bdd.crowd.exception.LoginAcctAlreadyInUseException;
import com.bdd.crowd.exception.LoginAcctAlreadyInUseFroeUpdateException;
import com.bdd.crowd.exception.LoginFailedException;
import com.bdd.crowd.mapper.AdminMapper;
import com.bdd.crowd.service.api.AdminService;
import com.bdd.crowd.utils.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author banddong
 * @create 2020-08-16 15:14
 * Admin接口实现类
 */
@Service
public class AdminServiceImpl implements AdminService {

    // 注入mapper层
    @Autowired
    private AdminMapper adminMapper;

    // 捕获异常信息
    private Logger logger = LoggerFactory.getLogger(AdminService.class);

    // 新增测试
    public void saveAdmin(Admin admin) {
        adminMapper.insert(admin);

        //Rolling back事务回滚
        //throw new RuntimeException();
    }

    // 一览
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    // 登录验证
    public Admin getAdminByloginAcct(String loginAcct, String userPswd) {

        // 1.根据登录账号查询Admin对象
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);

        List<Admin> list = adminMapper.selectByExample(adminExample);
        // 2.判断Admin对象是否为null
        if(list == null || list.size() == 0){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        if(list.size() > 1){//数据有问题
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        Admin admin = list.get(0);

        // 3.如果Admin对象为空则抛异常
        if(admin == null){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 4.不为空则取出Admin对象中的密码
        String pswd = admin.getUserPswd();

        // 5.将表单提交的密码进行加密
        String md5UserPswd = CrowdUtil.md5(userPswd);

        // 6.Admin对象中的密码和表单密码进行比较
        if(!Objects.equals(pswd, md5UserPswd)){
            // 7.密码不匹配抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 8.密码匹配返回Admin对象
        return admin;
    }

    // 页面一览,分页显示
    public PageInfo<Admin> pageInfo(String keyword, Integer pageNum, Integer pageSize) {

        // 1.调用PageHelper的静态方法开启功能(传入 开始数，每页最大数)
        // 这里充分体现了PageHelper的“非侵入性”设计，原本要做的查询不必有任何修改
        PageHelper.startPage(pageNum, pageSize);

        // 2.执行查询
        List<Admin> list = adminMapper.selectAdminByKeyword(keyword);

        // 3.封装到PageInfo中
        return new PageInfo<Admin>(list);
    }

    // 执行删除操作
    public void removeAdminById(Integer adminId, HttpSession session) {

        Admin admin1 = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);

        // 数据库是int类型，页面是Integer类型
        int a = admin1.getId();
        int b = adminId;

        if(a == b){
            throw new NullPointerException(CrowdConstant.MESSAGE_NOT_MY_DELETE);
        }else{
            adminMapper.deleteByPrimaryKey(adminId);
        }


    }

    // 新增
    public void insertAdmin(Admin admin) {

        // 1.密码加密
        String userPswd = CrowdUtil.md5(admin.getUserPswd());
        admin.setUserPswd(userPswd);

        // 2.创建时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(date);
        admin.setCreateTime(createTime);

        // 3.执行添加操作
        try {
            // 用户不存在
            adminMapper.insert(admin);
        } catch (Exception e){
            // 用户名存在
            e.printStackTrace();

            logger.info("异常全类名="+e.getClass().getName());

            //判断异常
            if(e instanceof DuplicateKeyException){
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
    }

    // 修改前查询
    @Override
    public Admin getAdminByAdminId(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    // 修改
    @Override
    public void updateAdmin(Admin admin) {

        // Selective表示选择更新，对于null值字段不更新
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            // 用户名存在
            e.printStackTrace();

            logger.info("异常全类名="+e.getClass().getName());

            //判断异常
            if(e instanceof DuplicateKeyException){
                throw new LoginAcctAlreadyInUseFroeUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
    }


}
